var businessBillInfo=unescape(T.p("businessBillInfo"));
var businessBillInfo = JSON.parse(businessBillInfo);
console.log("businessBillInfo:");
console.log(businessBillInfo);

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'erp/businessbillinfo/list',
        datatype: "json",
        colModel: [			
			{ label: 'businessBillInfoId', name: 'businessBillInfoId', index: 'business_bill_info_id', width: 50, key: true,hidden:true },
			{ label: '订单编号', name: 'billCode', index: 'bill_code', width: 80 }, 			
			{ label: '订单日期', name: 'billDate', index: 'bill_date', width: 80 }, 			
			{ label: '客户编码', name: 'customerCode', index: 'customer_code', width: 80 }, 			
			{ label: '送货地点', name: 'deliveryAddress', index: 'delivery_address', width: 80 }, 			
			{ label: '送货部门', name: 'deliveryPart', index: 'is_forbiden', width: 80 }, 			
			{ label: '客户PO', name: 'customerPo', index: 'customer_po', width: 80 }, 			
			{ label: '付款期', name: 'paymentMethod', index: 'payment_method', width: 80 }, 			
			{ label: '货币', name: 'currencyType', index: 'currency_type', width: 80 }, 			
			{ label: '总数量', name: 'totalNum', index: 'total_num', width: 80 }, 			
			{ label: '总金额', name: 'totalPrice', index: 'total_price', width: 80 }, 			
			{ label: '创建人', name: 'createBy', index: 'create_by', width: 80 }, 			
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        rules: {
        	billCode: [
            { required: true, message: '请输入订单编号', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          billDateStr: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
          customerCode: [
            { required: true, message: '请选择客户', trigger: 'change' }
          ],
          customerName: [
            { required: true, message: '请选择客户', trigger: 'change' }
          ],
          deliveryAddress: [
            { required: true, message: '请输入送货地址', trigger: 'blur' }
          ],
          deliveryPart: [
            { required: true, message: '请输入送货部门', trigger: 'blur' }
          ],
          customerPo: [
            { required: true, message: '请输入客户PO', trigger: 'blur' }
          ],
          paymentMethod: [
            { required: true, message: '请选择付款期', trigger: 'change' }
          ],
          currencyType: [
            { required: true, message: '请选择货币', trigger: 'change' }
          ]
        },
		showList: true,
		title: null,
		formData: {
			billCode: '',
			billDateStr: new Date(),
			deliveryAddress: '',
			deliveryPart: '',
			customerPo: '',
			customerCode: '',
			customerName: '',
			paymentMethod:	'',
			currencyType: '',
			customerInfoId: ''
		},
		businessInfoList: [],
		multipleSelection: [],
	    customerVO: {},
	    paymentMethodOptions: [],
	    currencyTypeOptions: [],
        customerList: [],
        customerPriceList: [],
        
	},
	created(){
		if(businessBillInfo){
			this.showList = false;
            this.title = "修改";
            this.getInfo(businessBillInfo.businessBillInfoId)
            this.getBusinessBillList(businessBillInfo.businessBillInfoId);
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.clearAllData();
			vm.showList = false;
			vm.title = "新增";
			this.$refs["ruleForm"].resetFields();
		},
		update: function (event) {
			var businessBillInfoId = getSelectedRow();
			if(businessBillInfoId == null){
				return ;
			}
			this.$refs["ruleForm"].resetFields();
			vm.showList = false;
            vm.title = "修改";
            vm.getInfo(businessBillInfoId);
            this.getBusinessBillList(businessBillInfoId);
		},
		saveOrUpdate: function (event) {
			//校验
			var passFlag=false;
			this.$refs["ruleForm"].validate((valid) => {
		          if (valid) {
		        	  passFlag=true;
		          } else {
		            console.log('error submit!!');
		            return false;
		          }
		        });
			console.log(vm.formData);
			if(!passFlag){
				return;
			}
			vm.formData.billDateStr=getFormatDate(this.formData.billDateStr);
//			for(var i=0;i<this.customerList.length;i++){
//				if(this.customerCode==this.customerList[i].customerCode){
//					this.customerVO=this.customerList[i];
//					break;
//				}
//			}
			vm.formData.status=1;
			
			var url = vm.formData.businessBillInfoId == null ? "erp/businessbillinfo/save" : "erp/businessbillinfo/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.formData),
			    success: function(r){
			    	if(r.code === 0){
			    		if(event=="billadd"){
			    			window.location.href="businessbill.html?businessBillInfo="+escape(JSON.stringify(r.businessBillInfo));
			    		}else{
			    			alert('操作成功', function(index){
			    				vm.getInfo(r.businessBillInfo.businessBillInfoId);
							});
			    		}
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var businessBillInfoIds = getSelectedRows();
			if(businessBillInfoIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "erp/businessbillinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(businessBillInfoIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(businessBillInfoId){
			$.get(baseURL + "erp/businessbillinfo/info/"+businessBillInfoId, function(r){
                vm.formData = r.businessBillInfo;
                vm.formData.billDateStr = new Date(r.businessBillInfo.billDate);
                vm.formData.billCode = r.businessBillInfo.billCode==null?"":r.businessBillInfo.billCode;
                vm.formData.customerCode = r.businessBillInfo.customerCode==null?"":r.businessBillInfo.customerCode;
                vm.formData.customerName = r.businessBillInfo.customerName==null?"":r.businessBillInfo.customerName;
                vm.formData.deliveryAddress = r.businessBillInfo.deliveryAddress==null?"":r.businessBillInfo.deliveryAddress;
                vm.formData.deliveryPart = r.businessBillInfo.deliveryPart==null?"":r.businessBillInfo.deliveryPart;
                vm.formData.customerPo = r.businessBillInfo.customerPo==null?"":r.businessBillInfo.customerPo;
                vm.formData.paymentMethod = r.businessBillInfo.paymentMethod==null?"":r.businessBillInfo.paymentMethod;
                vm.formData.currencyType = r.businessBillInfo.currencyType==null?"":r.businessBillInfo.currencyType;
                
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		changeCustomer:function(type){
			if(type==1){
				for(var i=0;i<this.customerList.length;i++){
					if(this.formData.customerCode==this.customerList[i].customerCode){
						this.customerVO=this.customerList[i];
						vm.formData.deliveryAddress=this.customerVO.deliveryAddress;
						vm.formData.customerName=this.customerVO.customerName;
						vm.formData.customerInfoId=this.customerVO.customerInfoId;
						break;
					}
				}
			}else{
				for(var i=0;i<this.customerList.length;i++){
					if(this.formData.customerName==this.customerList[i].customerName){
						this.customerVO=this.customerList[i];
						vm.formData.deliveryAddress=this.customerVO.deliveryAddress;
						vm.formData.customerCode=this.customerVO.customerCode;
						vm.formData.customerInfoId=this.customerVO.customerInfoId;
						break;
					}
				}
			}
			
			//this.getCustomerPrice(this.customerVO.customerInfoId);
		},
//		getCustomerPrice:function(customerInfoId){
//			$.get(baseURL + "erp/customerprice/priceinfo/"+customerInfoId, 
//			        function(r){
//		                if(r.code==0){
//		                	vm.customerPriceList=r.customerPriceList;
//		                }
//		            }
//		        );
//		},
		getCustomerList: function(){
			$.get(baseURL + "erp/customerinfo/list", 
				{
			        page:{"currPage":1,"limit":10}
			    },
			    function(r){
			        if(r.code==0){
			        	vm.customerList=r.page.list;
			        }
			    }
			);
		},
		getPayMethodList: function(){
			$.get(baseURL + "erp/baseparam/findInfoByCode", 
					{
						"paramCode":"PAYMENT_METHOD"
					},
			        function(r){
		                if(r.code==0){
		                	vm.paymentMethodOptions=r.list;
		                }
		            }
		        );
		},
		getCurrencyTypeList: function(){
			$.get(baseURL + "erp/baseparam/findInfoByCode", 
					{
						"paramCode":"CURRENCY_TYPE"
					},
			        function(r){
		                if(r.code==0){
		                	vm.currencyTypeOptions=r.list;
		                }
		            }
		        );
		},
		clearAllValidate:function(){
			this.$refs["ruleForm"].clearValidate();
		},
	    getBusinessBillList: function(businessBillInfoId){
	    	console.log(businessBillInfoId);
			$.get(baseURL + "erp/businessbill/listbybill", 
				{
			        "businessBillInfoId":businessBillInfoId
			    },
			    function(r){
			        if(r.code==0){
			        	vm.businessInfoList=r.list;
			        }
			    }
			);
		},
		billadd: function(){
			var businessBillInfoId=vm.formData.businessBillInfoId;
			if(businessBillInfoId==null || businessBillInfoId==undefined || businessBillInfoId==''){
				this.saveOrUpdate("billadd");
				return;
			}
			window.location.href="businessbill.html?businessBillInfo="+escape(JSON.stringify(vm.formData));
		},
		billupdate: function (event) {
			if(this.multipleSelection.length!=1){
				alert("请选择一项");
				return;
			}
			console.log(this.multipleSelection[0]);
			window.location.href="businessbill.html?businessBillInfo="+escape(JSON.stringify(vm.formData))+"&businessBill="+escape(JSON.stringify(this.multipleSelection[0]));
		},
		billdel: function (event) {
			
			if(this.multipleSelection.length==0){
				alert("请选择一项");
				return;
			}
			var businessBillIds = [];
			for(var i=0;i<this.multipleSelection.length;i++){
				businessBillIds.push(this.multipleSelection[i].businessBillId);
			}
			if(businessBillIds.length==0){
				return ;
			}
			console.log(businessBillIds);
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "erp/businessbill/delete",
                    contentType: "application/json",
				    data: JSON.stringify(businessBillIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								// 刷新列表
								vm.getBusinessBillList(vm.formData.businessBillInfoId);
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		handleSelectionChange:function(val){
			this.multipleSelection = val;
		},
		selectRow: function(row){
			if (row) {
	          this.$refs.multipleTable.toggleRowSelection(row);
	        } else {
	          this.$refs.multipleTable.clearSelection(row);
	        }
		},
		clearAllData:function(){
			this.businessInfoList = [];
			this.multipleSelection = [];
			this.customerVO = {};
			this.formData = {
				billCode: '',
				billDateStr: new Date(),
				deliveryAddress: '',
				deliveryPart: '',
				customerPo: '',
				customerCode: '',
				customerName: '',
				paymentMethod:	'',
				currencyType: '',
				customerInfoId: ''
			}
		},
		exportData:function(){
			var expUrl=baseURL + "erp/export/exportBillInfoData";
			$('#exportData').attr( 'href' ,  expUrl ) ;
			$("#exportData").click();
		},
		print:function(){
			html2canvas($("#gridDIV")).then(function(canvas) {
			    //document.body.appendChild(canvas);
			    var dataURL =canvas.toDataURL("image/png");
			    $("#yulan").attr('src',dataURL);
			});
//			html2canvas(document.getElementById("billInfoTable"),{ // $(".myImg")是你要复制生成canvas的区域，可以自己选
//		        onrendered:function(canvas){
//		        	debugger;
//		              dataURL =canvas.toDataURL("image/png");
//		             $("#billInfoTable").append(canvas);
//		              console.log(dataURL);
//
////		              //下载图片
//		              $('#down_button').attr( 'href' ,  dataURL ) ;
//		              $('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
//		          },
//		          width:320,
//		          height:400
//		      });
		}
	},
	mounted() {
	      this.getCustomerList();
		  this.getPayMethodList();
		  this.getCurrencyTypeList();
	      
	}
});

//日期格式化
function getFormatDate(date) {
    //var date = new Date();
	if(date==undefined || date==null || date==""){
		return "";
	}
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}